<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #addressShow="{ model, field }">
        <a-button type="primary" @click="showMap">新增地址</a-button>
        <Table
          :dataSource="model[field]"
          :columns="columns"
          :pagination="false"
          row-key="serialNumber"
        >
          <template #action="{ record }">
            <a-button type="link" @click="editMap(record, '编辑')">编辑</a-button>
            <a-button type="link" @click="deleteMap(record)">删除</a-button>
          </template>
        </Table>
      </template>
      <template #attendanceType="{ model, field }">
        <RadioGroup
          v-model:value="model[field]"
          :disabled="type == 'add' ? false : true"
          @change="radioChange"
        >
          <Radio value="FIXED_ATTENDANCE">固定考勤</Radio>
          <Radio value="FREEDOM_ATTENDANCE">自由考勤</Radio>
        </RadioGroup>
        <div
          style="margin-top: 12px"
          v-if="model[field] === 'FIXED_ATTENDANCE' || model[field] === 'FREEDOM_ATTENDANCE'"
        >
          <p v-if="model[field] === 'FIXED_ATTENDANCE'" style="color: red"
            >适用于固定上下时间的人员，例如早八点上班，下午六点下班。</p
          >
          <p v-if="model[field] === 'FREEDOM_ATTENDANCE'" style="color: red"
            >适用于不固定上下班时间的人员。</p
          >
          <Card>
            <Form
              :model="punchInfo"
              :label-col="{ span: 8 }"
              layout="inline"
              :rules="rules"
              ref="formRef"
            >
              <FormItem
                v-if="model[field] === 'FIXED_ATTENDANCE'"
                label="上班时间"
                name="clockInTime"
                :wrapper-col="{ span: 4 }"
              >
                <TimePicker
                  v-model:value="punchInfo.clockInTime"
                  format="HH:mm"
                  valueFormat="HH:mm"
                  style="width: 200px"
                />
              </FormItem>
              <FormItem
                v-if="model[field] === 'FIXED_ATTENDANCE'"
                label="下班时间"
                :wrapper-col="{ span: 4 }"
                name="clockOffTime"
              >
                <TimePicker
                  v-model:value="punchInfo.clockOffTime"
                  format="HH:mm"
                  valueFormat="HH:mm"
                  style="width: 200px"
                />
              </FormItem>
              <FormItem
                v-if="model[field] === 'FREEDOM_ATTENDANCE'"
                label="晚于几点记为次日考勤"
                :label-col="{ span: 10 }"
                :wrapper-col="{ span: 4 }"
                name="cutOffTime"
              >
                <TimePicker
                  v-model:value="punchInfo.cutOffTime"
                  format="HH:mm:ss"
                  valueFormat="HH:mm:ss"
                  style="width: 200px"
                />
              </FormItem>
              <FormItem
                label="设置工作日"
                name="weekday"
                :label-col="{ span: 3 }"
                :wrapper-col="{ span: 14 }"
              >
                <CheckboxGroup
                  v-model:value="punchInfo.weekday"
                  name="checkboxgroup"
                  :options="workDayOptions"
                />
              </FormItem>
              <FormItem
                label=""
                name="legalHolidayState"
                v-if="model[field] === 'FIXED_ATTENDANCE'"
              >
                <Checkbox v-model:checked="punchInfo.legalHolidayState">同步国家节假日</Checkbox>
              </FormItem>
              <FormItem name="offsiteClockState" label="">
                <Checkbox v-model:checked="punchInfo.offsiteClockState">是否允许异地打卡</Checkbox>
              </FormItem>
            </Form>
          </Card>
        </div>
      </template>
    </BasicForm>
  </BasicDrawer>
  <BasicModal v-model:visible="visible" title="选择位置" @ok="handleOk" width="800px">
    <Map
      ref="childComp"
      :searchMap="searchMap"
      :isClick="isClick"
      :serviceAddress="address"
      :lat="latitude"
      :lng="longitude"
      :isCircle="isCircle"
      :distance="distance"
      :isDistance="true"
    />
  </BasicModal>
</template>
<script lang="ts">
import { defineComponent, ref, computed, unref, reactive, toRefs, onMounted } from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from './tableData';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import moment, { Moment } from 'moment';
import { BasicModal } from '/@/components/Modal';
import Map from '/@/components/Map/Map.vue';
import {
  Table,
  RadioGroup,
  Card,
  Radio,
  Form,
  FormItem,
  CheckboxGroup,
  TimePicker,
  Checkbox,
} from 'ant-design-vue';

export default defineComponent({
  name: 'MenuDrawer',
  components: {
    BasicDrawer,
    BasicForm,
    Map,
    BasicModal,
    Table,
    RadioGroup,
    Card,
    Radio,
    Form,
    FormItem,
    CheckboxGroup,
    TimePicker,
    Checkbox,
  },
  props: {
    type: {
      type: String,
      default: () => {
        return 'add';
      },
    },
  },
  emits: ['success', 'register'],
  setup(props, { emit }) {
    const isUpdate = ref(true);
    const childComp = ref(null);
    const formRef = ref();
    // let checkWorkDay = async (rule: RuleObject, value: any) => {
    //   if (value && value.length) {
    //     return Promise.resolve();
    //   } else {
    //     return Promise.reject('请设置工作日');
    //   }
    // };
    const data: any = reactive({
      visible: false,
      searchMap: true,
      isClick: true,
      isCircle: true,
      longitude: 0,
      latitude: 0,
      address: '',
      distance: 300,
      formData: [],
      adID: null,
      typeMap: 'add',
      workDayOptions: [
        {
          label: '星期一',
          value: '1',
        },
        {
          label: '星期二',
          value: '2',
        },
        {
          label: '星期三',
          value: '3',
        },
        {
          label: '星期四',
          value: '4',
        },
        {
          label: '星期五',
          value: '5',
        },
        {
          label: '星期六',
          value: '6',
        },
        {
          label: '星期日',
          value: '7',
        },
      ],
      rules: {
        clockInTime: [{ required: true, message: '请填写', trigger: 'blur' }],
        clockOffTime: [{ required: true, message: '请填写', trigger: 'blur' }],
      },
      columns: [
        {
          title: '考勤地址',
          dataIndex: 'address',
        },
        {
          title: '有效范围',
          dataIndex: 'distance',
        },
        {
          title: '操作',
          key: 'action',
          slots: { customRender: 'action' },
        },
      ],
      punchInfo: {
        clockInTime: null,
        clockOffTime: null,
        cutOffTime: '23:59:59',
        weekday: [],
        legalHolidayState: false,
        offsiteClockState: false,
      },
    });

    const [registerForm, { resetFields, setFieldsValue, appendSchemaByField, validate, setProps }] =
      useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });
    const formId = ref(null);
    const [registerDrawer, { setDrawerProps }] = useDrawerInner(async (dataList) => {
      resetFields();
      setDrawerProps({ confirmLoading: false });
      setProps({
        mergeDynamicData: { propsType: props.type },
      });
      isUpdate.value = !!dataList?.isUpdate;
      formId.value = props.type === 'edit' ? dataList.record.id : null;
      if (unref(isUpdate)) {
        data.punchInfo = { ...dataList.record };
        if (dataList.record.legalHolidayState === 'SYNC_HOLIDAY') {
          data.punchInfo.legalHolidayState = true;
        } else {
          data.punchInfo.legalHolidayState = false;
        }
        if (dataList.record.offsiteClockState === 'ALLOW_OFFSITE') {
          data.punchInfo.offsiteClockState = true;
        } else {
          data.punchInfo.offsiteClockState = false;
        }
        if (data.punchInfo.attendanceType == 'FIXED_ATTENDANCE') {
        }
        data.punchInfo.weekday =
          data.punchInfo.weekday && data.punchInfo.weekday.length
            ? data.punchInfo.weekday.split(',')
            : [];
        let list = dataList.record.attendRulePositionList;
        console.log('我是编辑的值', data.punchInfo);
        let formData = [] as any;
        if (list && list.length) {
          list.forEach((i, index) => {
            formData.push({
              fId: index,
              address: i.position,
              longitude: i.longitude,
              latitude: i.latitude,
              distance: i.range * 1,
            });
          });
          dataList.record.formData = formData;
          data.formData = formData;
        }
        setFieldsValue({
          ...dataList.record,
          // punchInfo: {attendanceType: 'FIXED_ATTENDANCE' },
          deptId: dataList.record.deptId || [],
          type: dataList.record.deptId ? 2 : 1,
        });
      } else {
        data.formData = [];
        data.punchInfo = {
          clockInTime: null,
          clockOffTime: null,
          cutOffTime: null,
          weekday: [],
          legalHolidayState: false,
          offsiteClockState: false,
        };
      }
    });
    const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

    //展示地图(增加)
    function showMap() {
      data.typeMap = 'add';
      data.visible = true;
    }
    //弹框点击确定
    const handleOk = () => {
      let info = childComp.value.data;
      let fId = data.formData.length;
      let mapData;
      if (info && info.lat && info.lng) {
        mapData = {
          address: info.address ? info.address : info.serviceAddress,
          longitude: info.lng,
          latitude: info.lat,
          distance: info.distance,
        };
      }

      if (data.typeMap == 'add') {
        mapData.fId = fId;
        data.formData.push(mapData);
        data.formData.forEach((i, iIndex) => {
          i.fId = iIndex;
        });
      } else {
        mapData.fId = data.adID;
        data.formData.splice(data.adID, 1, mapData);
        data.formData.forEach((s, sIndex) => {
          s.fId = sIndex;
        });
      }

      setFieldsValue({
        formData: data.formData,
      });
      data.visible = false;
    };
    //编辑地址
    function editMap(val) {
      data.adID = val.fId;
      data.longitude = val.longitude;
      data.latitude = val.latitude;
      data.address = val.address;
      data.distance = val.distance;
      data.typeMap = 'edit';
      data.visible = true;
      console.log('我是编辑', val);
    }

    //删除地址
    function deleteMap(val) {
      console.log('我是删除', val);
      data.formData.splice(val.fId, 1);
      data.formData.forEach((d, dIndex) => {
        d.fId = dIndex;
      });
      data.longitude = 0;
      data.latitude = 0;
      data.address = '';
      data.distance = 300;
    }

    //我是选择考勤类型
    function radioChange(val){
      console.log('我是考勤类型',val);
      if(val.target.value=='FREEDOM_ATTENDANCE'){
        data.punchInfo.weekday = ['1','2','3','4','5','6','7']
      }else{
        data.punchInfo.weekday = [];
      }
    }
    async function handleSubmit() {
      try {
        const values1 = await formRef.value.validate();
        const values = await validate();
        setDrawerProps({ confirmLoading: true });
        let params = { ...values, ...values1 }; // ...values1
        if (params.attendanceType == 'FIXED_ATTENDANCE') {
          if (params.legalHolidayState) {
            params.legalHolidayState = 'SYNC_HOLIDAY';
          } else {
            params.legalHolidayState = 'NOT_SYNC_HOLIDAY';
          }
        }
        if (params.offsiteClockState) {
          params.offsiteClockState = 'ALLOW_OFFSITE';
        } else {
          params.offsiteClockState = 'FORBID_OFFSITE';
        }
        // return
        params.weekday = params.weekday.join(',');
        let list = [] as any;
        if (params.formData && params.formData.length) {
          params.formData.forEach((i) => {
            list.push({
              position: i.address,
              latitude: i.latitude,
              longitude: i.longitude,
              range: i.distance,
            });
          });
        }
        params.attendRulePositionList = list;
        delete params.formData;
        delete params.type;
        console.log('我是操作', params);

        // return;
        if (formId.value) {
          params.id = formId.value;
        }
        emit('success', params);
        data.formData = [];
      } finally {
        setDrawerProps({ confirmLoading: false });
      }
    }
    return {
      ...toRefs(data),
      formRef,
      registerDrawer,
      registerForm,
      getTitle,
      handleSubmit,
      showMap,
      handleOk,
      deleteMap,
      editMap,
      childComp,
      radioChange,
    };
  },
});
</script>
